로딩 중이에요... 🐣
[코담]
웹개발·실전 프로젝트·AI까지, 파이썬·장고의 모든것을 담아낸 강의와 개발 노트
06 View와 Template 연결, URL 매핑 이해 | ✅ 편저: 코담 운영자
Django 웹 프로그래밍 강좌 6강 - View와 Template 연결, URL 매핑 이해 (Django 5.2 기준)
이 강의는 Django 공식 문서의 2.2 튜토리얼 내용을 바탕으로 진행되며, Django 5.2 버전에 맞춰 코드를 업그레이드하여 설명합니다.
📚 공식문서 주소: https://docs.djangoproject.com/ko/5.2/intro/tutorial03/
1. View란 무엇인가?
Django에서 View는 사용자의 요청(request)에 대해 적절한 응답(response)을 반환하는 비즈니스 로직 처리 공간입니다.
- 요청 → URLConf → View → 응답 (HTML/JSON 등)
- View는 데이터를 처리하거나 템플릿을 호출합니다
2. 기본 View 함수 구조
예시 (polls/views.py
)
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
request
객체를 받아HttpResponse()
를 통해 문자열 또는 HTML을 반환합니다.
실제 웹 애플리케이션에서는 템플릿과의 연동이 일반적입니다.
3. URLconf 연결하기
사용자가 특정 URL로 요청했을 때 어떤 View가 실행될지 연결해주는 설정입니다.
polls/urls.py
from django.urls import path
from . import views
app_name = "polls"
urlpatterns = [
path("", views.index, name="index"),
path("<int:question_id>/", views.detail, name="detail"),
path("<int:question_id>/results/", views.results, name="results"),
path("<int:question_id>/vote/", views.vote, name="vote"),
]
<int:question_id>
는 URL에서 정수형 데이터를 받아 View로 전달name
속성은 템플릿에서 URL을 참조할 때 사용됩니다
mysite/urls.py
from django.urls import include, path
from django.contrib import admin
urlpatterns = [
path("polls/", include("polls.urls")),
path("admin/", admin.site.urls),
]
4. View에서 템플릿으로 데이터 전달
View는 단순한 문자열 응답 대신, 템플릿을 통해 동적인 HTML 페이지를 구성할 수 있습니다.
템플릿 디렉토리 구조
polls/
├── templates/
│ └── polls/
│ ├── index.html
│ ├── detail.html
Django는 앱 이름과 일치하는 하위 디렉토리를 통해 템플릿을 식별하므로, 반드시
templates/polls/
구조를 따라야 합니다.
View에서 템플릿 사용 (views.py
)
from django.shortcuts import render
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by("-pub_date")[:5]
context = {"latest_question_list": latest_question_list}
return render(request, "polls/index.html", context)
render()
함수는 템플릿을 불러오고 context를 전달하여 HTML 응답을 생성합니다.context
는 템플릿에서 사용할 데이터의 사전(dict)입니다.
템플릿 예시 (polls/templates/polls/index.html
)
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
{% url %}
템플릿 태그는 URL을 name 기반으로 연결합니다. 하드코딩을 피하고 유지보수성을 높입니다.
5. 상세 페이지 View 및 예외 처리
views.py
from django.shortcuts import get_object_or_404
from .models import Question
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, "polls/detail.html", {"question": question})
get_object_or_404()
는 객체가 존재하지 않으면 자동으로Http404
예외를 발생시킵니다.- 데이터가 존재하는 경우에만 템플릿으로 넘깁니다.
polls/templates/polls/detail.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
question.choice_set.all
은 역참조를 통해 연결된 Choice 객체들을 가져옵니다.
6. 개발 생산성 향상 Tip
render()
함수는HttpResponse
보다 간결하고 템플릿을 효과적으로 사용할 수 있습니다.{% url %}
태그를 이용해 URL 하드코딩을 방지합니다.get_object_or_404()
를 사용해 예외 처리 코드를 줄일 수 있습니다.- 반복되는 패턴은 추후
Generic View
로 대체 가능
마무리 요약
- View는 비즈니스 로직을 처리하고 응답을 반환하는 핵심 구성 요소입니다.
- URLconf를 통해 URL 요청과 View를 연결합니다.
- 템플릿 시스템을 통해 HTML 화면과 로직을 분리할 수 있습니다.
- 컨텍스트를 통해 템플릿에 데이터를 전달하며,
- 예외 처리와 URL reverse 기능을 통해 유지보수성을 높입니다.
다음 강의 예고
7강에서는 Form 처리와 Generic View를 활용하여 사용자 입력을 처리하고, 더 짧고 효율적인 뷰를 작성하는 방법을 배웁니다.
감사합니다.